package com.yx.customized;

import android.content.Context;
import android.content.res.Resources;
import android.os.Build;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;

/**
 * Created : Yx
 * Time : 2019/12/4 18:11
 * Describe :
 */
public class LevelView extends LinearLayout implements View.OnClickListener {
    private int level = 0;

    private boolean isClicks = true;

    public LevelView(Context context) {
        super(context);
    }

    public LevelView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        setOrientation(HORIZONTAL);
        setGravity(Gravity.CENTER_VERTICAL);
        for (int i = 0; i < 5; i++) {
            ImageView imageView = new ImageView(context);
            imageView.setImageResource(R.drawable.star_s);
            LayoutParams layoutParams = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
            layoutParams.rightMargin = dpToPx(8);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
                imageView.setId(View.generateViewId());
            }
            addView(imageView, layoutParams);
            imageView.setOnClickListener(this);
        }
    }

    public void setLevel(int level, boolean isClicks) {
        this.level = level;
        this.isClicks = isClicks;
        int tempIndex = level - 1;
        for (int i = 0; i < getChildCount(); i++) {
            ImageView imageView = (ImageView) this.getChildAt(i);
            imageView.setImageResource((i <= tempIndex ? R.drawable.star_s : R.drawable.star_n));
            imageView.setClickable(isClicks);
        }
    }

    /***
     * 小图
     * @param level
     */
    public void setSimalLevel(int level, boolean isClicks) {
        this.level = level;
        int tempIndex = level - 1;
        for (int i = 0; i < getChildCount(); i++) {
            ImageView imageView = (ImageView) this.getChildAt(i);
            imageView.setImageResource((i <= tempIndex ? R.drawable.star_s_s : R.drawable.star_s_n));
            imageView.setClickable(isClicks);
        }
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        level = 0;
        for (int i = 0; i < getChildCount(); i++) {
            if (id == getChildAt(i).getId()) {
                level = i + 1;
                break;
            }
        }
        setLevel(level, isClicks);
    }

    public int getLevel() {
        return level;
    }

    public int dpToPx(int dp) {
        float scale = Resources.getSystem().getDisplayMetrics().density;
        return (int) (dp * scale + 0.5f);
    }
}
